#!/bin/bash

echo "=== 在Linux中安装Docker ==="

# 检查是否为root用户
if [ "$EUID" -ne 0 ]; then
    echo "请使用root权限运行此脚本"
    exit 1
fi

# 更新系统包
echo "更新系统包..."
yum update -y || apt update -y

# 卸载旧版本Docker
echo "卸载旧版本Docker..."
yum remove -y docker docker-client docker-client-latest docker-common docker-latest docker-latest-logrotate docker-logrotate docker-engine || \
apt remove -y docker docker-engine docker.io containerd runc

# 安装必要的依赖
echo "安装必要的依赖..."
yum install -y yum-utils device-mapper-persistent-data lvm2 || \
apt install -y apt-transport-https ca-certificates curl gnupg lsb-release

# 添加Docker官方GPG密钥
echo "添加Docker官方GPG密钥..."
curl -fsSL https://download.docker.com/linux/centos/gpg | gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg || \
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg

# 添加Docker仓库
echo "添加Docker仓库..."
if [ -f /etc/redhat-release ]; then
    # CentOS/RHEL
    yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
else
    # Ubuntu/Debian
    echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null
fi

# 安装Docker
echo "安装Docker..."
if [ -f /etc/redhat-release ]; then
    yum install -y docker-ce docker-ce-cli containerd.io
else
    apt update -y
    apt install -y docker-ce docker-ce-cli containerd.io
fi

# 启动Docker服务
echo "启动Docker服务..."
systemctl start docker
systemctl enable docker

# 安装Docker Compose
echo "安装Docker Compose..."
curl -L "https://github.com/docker/compose/releases/download/v2.20.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
chmod +x /usr/local/bin/docker-compose

# 创建docker用户组并添加当前用户
echo "配置Docker用户组..."
usermod -aG docker $SUDO_USER

# 验证安装
echo "验证Docker安装..."
docker --version
docker-compose --version

echo "✓ Docker安装完成！"
echo "请重新登录或运行 'newgrp docker' 来应用用户组权限" 